﻿// news ticket
var newsTicket = null;
var NewsTicket = function(options) {
    var holder = $(options.holderID),
            items = options.items,
            timeOut = options.timeOut,

            curItem = 0,
            curTimer = null;

    return {
        stop: function() {

        },

        start: function() {
            if (items.length > 0 && holder.length > 0) {
                holder.fadeOut(500, function() {
                    holder.html(items[curItem].msg);
                });
                holder.fadeIn();

                curItem++;
                if (curItem > items.length - 1)
                    curItem = 0;

                setTimeout("newsTicket.start()", 5000);
            }
            else {
                holder.parent().hide();
            }
        }
    }
}

// shoutbox
var _shoutbox_cur_page = 1;
function shoutbox_show(id, show) {
    var data = {
        'action': 'show',
        'id': id,
        'is_show': show
    };

    shoutbox_send(data, function(res) {
        if (res.success == 'ok') {
            shoutbox_list();
        }
        else {
            alert(res.message);
        }
    });
}

function shoutbox_save() {
    var msg = $('#shoutMessage').val();

    if (msg == '') {
        alert('Vui lòng nhập nội dung');
        $('#shoutMessage').focus();

        return;
    }

    $('#shoutButton').unbind('click').attr('disabled', true);


    var data = {
        'action': 'save',
        'msg': msg
    };

    shoutbox_send(data, function(res) {
        if (res.success == 'ok') {
            shoutbox_list(); // refresh list

            $('#shoutMessage').val("");
        }
        else {
            alert(res.message);
        }
    });

    $('#shoutButton').click(function(e) {
        shoutbox_save();
        e.preventDefault();
    }).attr('disabled', false);
}

function shoutbox_list(cur_page) {
    if (cur_page == null)
        cur_page = 1;

    _shoutbox_cur_page = 1;

    var data = {
        'action': 'list',
        'cur_page': cur_page
    };

    shoutbox_send(data, function(res) {
        if (res.success == 'ok') {
            $('#shoutbox_list').html(res.message);

            _shoutbox_bind();

            $('html,body').animate({ scrollTop: $('#message-area').offset().top }, { duration: 'slow', easing: 'swing' });
        }
        else {
            alert(res.message);
        }
    });

    return false;
}

function shoutbox_send(data, callback, error) {
    $.ajax({
        url: '/services/shoutbox.ashx',
        beforeSend: function(xhr) {
            xhr.setRequestHeader("gm-ajax-request", 'gm-ajax-request');
        },
        data: data,
        dataType: 'json',
        type: 'post',
        async: true,
        success: function(results) {
            if (callback) {
                callback(results);
            }
        },
        error: function(xhr) {
            if (error) {
                error();
            } else {
                alert('Xảy ra lỗi khi thực thi!');
            }
        }
    });
}

function shoutbox_mark(sender) {
    var id = _shoutbox_get_id(sender);
    if (id != null) {
        var data = {
            'action': 'show',
            'id': id,
            'is_show': '0'
        };

        shoutbox_send(data, function(res) {
            if (res.success == 'ok') {
                shoutbox_list(_shoutbox_cur_page); // refresh list
            }
            else {
                alert(res.message);
            }
        });
    }
}

function shoutbox_delete(sender) {
    var id = _shoutbox_get_id(sender);
    if (id != null) {
        if (confirm('Bạn muốn xóa tin nhắn này?')) {
            var data = {
                'action': 'delete',
                'id': id
            };

            shoutbox_send(data, function(res) {
                if (res.success == 'ok') {
                    shoutbox_list(_shoutbox_cur_page); // refresh list
                }
                else {
                    alert(res.message);
                }
            });
        }
    }
}

function shoutbox_answer_delete(sender) {
    var id = _shoutbox_answer_get_id(sender);
    if (id != null) {
        if (confirm('Bạn muốn xóa tin nhắn này?')) {
            var data = {
                'action': 'delete',
                'id': id
            };

            shoutbox_send(data, function(res) {
                if (res.success == 'ok') {
                    shoutbox_list(_shoutbox_cur_page); // refresh list
                }
                else {
                    alert(res.message);
                }
            });
        }
    }
}

function shoutbox_reply(sender) {
    var id = _shoutbox_get_id(sender);

    // get text message
    var div_parent = sender.closest('div.detail-message');
    var txt = div_parent.find('textarea');

    txt.toggle();
    txt.focus();
    txt.autoResize({ limit: 300, extraSpace: 0 });
}

function shoutbox_reply_save(sender) {
    var id = _shoutbox_get_id(sender);
    var msg = sender.val();

    if (msg == '') {
        alert('Vui lòng nhập nội dung');
        sender.focus();
        return;
    }

    var data = {
        'action': 'save',
        'parent': id,
        'msg': msg
    };

    shoutbox_send(data, function(res) {
        if (res.success == 'ok') {
            shoutbox_list(_shoutbox_cur_page); // refresh list

            $('#shoutMessage').val("");
        }
        else {
            alert(res.message);
        }
    });
}

function _shoutbox_get_id(sender) {
    var div_parent = sender.closest('div.detail-message');
    var id_obj = div_parent.find('input[type=hidden]');

    return id_obj.val();
}

function _shoutbox_answer_get_id(sender) {
    var id = sender.attr('id');
    id = id.replace(/answer-/ig, '');

    return id;
}

function _shoutbox_bind() {
    $('#shoutbox_list').find('div.detail-message').each(function() {
        var div_parent = $(this);

        div_parent.find('span.usr-msg-action').click(function() {
            if (isLoggedin == true) {
                shoutbox_reply($(this));
            }
            else {
                show_login();
            }
        });

        div_parent.find('span.usr-warning').click(function() {
            shoutbox_mark($(this));
        });

        div_parent.find('span.usr-delete').click(function() {
            shoutbox_delete($(this));
        });

        div_parent.find('textarea').keypress(function(e) {
            var code = (e.keyCode ? e.keyCode : e.which);
            if (code == 13) {
                if (isLoggedin == true) {
                    shoutbox_reply_save($(this));
                }
                else {
                    show_login();
                }
                e.preventDefault();
            }
        });

        div_parent.find('span.usr-delete-answer').each(function() {
            $(this).click(function() {
                shoutbox_answer_delete($(this));
            });
        });
    });
}

// common functions
function show_login() {
    loginDialog.show();

    $('#simple_dialog .close').click(function(e) {
        loginDialog.close();
        e.preventDefault();
    });
}

function header_menu(obj_selector) {
    obj_selector.hover(function() {
        $(this).addClass("hover");
        $('ul:first', this).css('visibility', 'visible');

    }, function() {
        $(this).removeClass("hover");
        $('ul:first', this).css('visibility', 'hidden');
    });
}

function set_filter_mode(mode) {
    // set cookies
    var date = new Date();
    date.setTime(date.getTime() + (24 * 60 * 60 * 1000)); // a month
    $.cookie('gm_filter_mode', mode, { expires: date, path: '/' });

    if (mode == 2)
        window.location.href = '/';
    else
        window.location.href = '/deals';

    return false;
}

function do_search() {
    var keyword = $('#query');
    if (keyword.length > 0) {
        if (keyword.val().length > 2) {
            window.location.href = '/search.aspx?query=' + encodeURIComponent(keyword.val());
        }
        else {
            alert('Từ khóa tìm kiếm quá ngắn');
            keyword.focus();
        }
    }
}

var upRequest = function(id) {
    var formData = 'id=' + id;
    $.ajax({
        url: '/services/upcoupon.ashx',
        beforeSend: function(xhr) {
            xhr.setRequestHeader("gm-ajax-request", 'gm-ajax-request');
        },
        data: formData,
        dataType: 'html',
        type: 'post',
        async: true,
        success: function(results) {
            if (results == 'OK')
                window.location = window.location;
            else
                alert('Xảy ra lỗi khi thực thi!');
        },
        error: function(xhr) {
            alert('Xảy ra lỗi khi thực thi!');
        }
    });
};

function get_images(ids_list) {
    var path = '/images/upload/';
    $.ajax({
        url: '/services/getimages.ashx',
        beforeSend: function(xhr) {
            xhr.setRequestHeader("gm-ajax-request", 'gm-ajax-request');
        },
        data: { ids: ids_list },
        dataType: 'json',
        type: 'post',
        async: true,
        success: function(results) {
            if (results.data != null) {
                for (var i = 0; i < results.data.length; i++) {
                    var image_id = '#img-' + results.data[i].id;
                    $(image_id).attr('src', path + results.data[i].path);
                }
            }
        },
        error: function(xhr) {
        }
    });
} 

var mailDialog;
var couponLinkDialog;
var vipCookiesName = 'vip_show';
var vipCookiesTime = 5; // 5 mins

jQuery(document).ready(function() {
    // set timer for coupon items
    setTime();

    // init news ticket
    newsTicket = new NewsTicket({
        holderID: '#news-tickets',
        items: newsList,
        timeOut: 1000
    });

    newsTicket.start();

    // init menus
    header_menu($('#menu_settings'));
    header_menu($('#menu_location'));
    header_menu($('#add-menu'));
    header_menu($('#menu_sites'));

    // register mail dialog
    mailDialog = new Giamua.RegisterMailDialog();
    $('#btnShowMailForm').click(function() {
        mailDialog.show();

        $('#simple_dialog .close').click(function(e) {
            mailDialog.close();
            e.preventDefault();
        });
    });

    // bind event for shoutbox login
    loginDialog = new Giamua.LoginDialog();
    $('#shoutbox_login').click(function(e) {
        show_login();
        e.preventDefault();
    });

    var default_text = 'Tìm voucher';
    $('#query').focus(function() {
        if ($(this).val() == default_text) {
            $(this).val('');
        }
    }).blur(function() {
        if ($(this).val() == '') {
            $(this).val(default_text);
        }
    }).val(default_text);
    // register search events
    $('#query').keypress(function(e) {
        var code = (e.keyCode ? e.keyCode : e.which);
        if (code == 13) {
            do_search();
            e.preventDefault();
        }
    });

    $('#search_btn').click(function(e) {
        do_search();
        e.preventDefault();
    });

    $('#show_search_form').click(function(e) {
        $('#gm_search').toggle();
        $('#query').focus();
        e.preventDefault();
    });

    // register coupon items events
    $('div.like').click(function() {
        var id = $(this).attr('id');
        id = id.replace('img-', '');
        upRequest(id);
    });

    $('div.item-detail').hover(
        function() {
            var container = $(this);
            var time = container.find('span.time');
            var timeLeft = time.attr('timeleft');
            if (timeLeft > 1) {
                container.find('div.like').css('visibility', 'visible');
            }
            container.find('div.comment').css('visibility', 'visible');
            container.find('div.hide-vip-btn').css('visibility', 'visible');
        },
        function() {
            var container = $(this);
            container.find('div.like').css('visibility', 'hidden');
            container.find('div.comment').css('visibility', 'hidden');
            container.find('div.hide-vip-btn').css('visibility', 'hidden');
        }
    );

    var btnVip = $('#hide-vip-btn');
    if (btnVip != null && btnVip.length > 0) {
        var cookieValue = $.cookie(vipCookiesName);
        if (cookieValue != null && cookieValue == 1) {
            $('#show-vip-item').show();
            $('div.vip-pan').hide();
        }
        else {
            $('#show-vip-item').hide();
            $('div.vip-pan').show();
        }

        btnVip.click(function(evt) {
            // set cookies
            var date = new Date();
            date.setTime(date.getTime() + (vipCookiesTime * 60 * 1000));
            $.cookie(vipCookiesName, 1, { expires: date, path: '/' });

            // show/hide div
            $('#show-vip-item').show();
            $('div.vip-pan').hide();

            evt.preventDefault();
        });

        $('#show-vip-item').click(function(evt) {
            $.cookie(vipCookiesName, null);

            // show/hide div
            $('#show-vip-item').hide();
            $('div.vip-pan').show();

            evt.preventDefault();
        });
    }

    // shoutbox events
    $('#shoutButton').click(function(e) {
        if (isLoggedin == true) {
            shoutbox_save();
        }
        else {
            show_login();
        }

        e.preventDefault();
    });

    $('#shoutMessage').maxlength();

    $('#shoutMessage').bind('focusin', function() {
        if (!isLoggedin) {
            show_login();
        }
    });

    var MAX_HEIGHT = 1250;
    var shoutbox_height = $('#shoutbox_list').height();
    if (shoutbox_height > MAX_HEIGHT) {
        var readmore = $('<div id="shoutbox_list_readmore" title="Nhấn để xem thêm" style="cursor:pointer;font-family:Verdana;font-size:11px;text-align:right;margin:5px 10px; 0px 0px;color: #0879A5;">Xem thêm ▼</div>');
        $('#message-area').append(readmore);
        $('#shoutbox_list').height(MAX_HEIGHT);
        $('#shoutbox_list').css('overflow', 'hidden');

        readmore.click(function() {
            $(this).hide();
            $('#shoutbox_list').css('height', 'auto');
        });
    }

    // bind event for shoutbox list
    _shoutbox_bind();

    //    if ($.browser.msie) {
    //        $('div.item-detail').each(function() {
    //            $(this).attr('unselectable', 'on').bind('selectstart', function(e) { e.preventDefault(); return false; });
    //        });
    //    }

    $(".vip-coupon-inner").jCarouselLite({
        vertical: true,
        auto: 3000,
        visible: 1,
        speed: 800,
        hoverPause: true
    });

    var cookieSitesSortValue = $.cookie('gm_sites_sort');
    if (cookieSitesSortValue != null && cookieSitesSortValue == 1) {
        showSitesABC();
    }
    else {
        showSitesDefault();
    }

    $('#btn-sort-abc').click(function() {
        showSitesABC();

        var date = new Date();
        date.setTime(date.getTime() + (24 * 60 * 60 * 1000)); // a month
        $.cookie('gm_sites_sort', 1, { expires: date, path: '/' });
    });

    $('#btn-sort-default').click(function() {
        showSitesDefault();

        var date = new Date();
        date.setTime(date.getTime() + (24 * 60 * 60 * 1000)); // a month
        $.cookie('gm_sites_sort', 0, { expires: date, path: '/' });
    });

    function showSitesDefault() {
        var btnDefault = $('#btn-sort-default');
        btnDefault.addClass('btn-sort-selected');
        btnDefault.removeClass('btn-sort');
        $('#sites-default').show();

        var btnABC = $('#btn-sort-abc');
        btnABC.addClass('btn-sort');
        btnABC.removeClass('btn-sort-selected');
        $('#sites-abc').hide();
    }

    function showSitesABC() {
        var btnABC = $('#btn-sort-abc');
        btnABC.addClass('btn-sort-selected');
        btnABC.removeClass('btn-sort');
        $('#sites-abc').show();

        var btnDefault = $('#btn-sort-default');
        btnDefault.addClass('btn-sort');
        btnDefault.removeClass('btn-sort-selected');
        $('#sites-default').hide();
    }
});